package cc.comac.mom.datahandlers.entity.soapreceive;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.ans.shaded.com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cc.comac.mom.dao.entity.QualityPclrTestInvoiceDao;
import cc.comac.mom.dao.entity.QualityQarCheckInvoiceDao;
import cc.comac.mom.dao.entity.QualitySapPurchaseOrderDao;
import cc.comac.mom.datahandlers.entity.QualitySapPurchaseOrderDataHandler;
import cc.comac.mom.entity.QualityPclrTestInvoiceEntity;
import cc.comac.mom.entity.QualityQarCheckInvoiceEntity;
import cc.comac.mom.entity.QualitySapPurchaseOrderEntity;
import cc.comac.mom.util.ResultBean;
import cc.comac.mom.util.TimeUtil;
import cc.comac.mom.util.soaputil.SoapCallUtil;

@Component
public class TestDataManageReceive {

	@Autowired
	private QualityPclrTestInvoiceDao qualityPclrTestInvoiceDao;
	
	@Autowired
	private QualityQarCheckInvoiceDao qualityQarCheckInvoiceDao;
	
	@Autowired
	private QualitySapPurchaseOrderDao qualitySapPurchaseOrderDao;
	@Autowired QualitySapPurchaseOrderDataHandler qualitySapPurchaseOrderDataHandler;
	// QAR将MAT实验任务发送给实验数据管理系统，由实验数据管理系统进行试验
	public void sentTestData(QualityPclrTestInvoiceEntity entity) {
		String myNamespace = "mom";
		String myNamespaceURI = "urn://www.comac.com/mom";
		try {
			// Create SOAP Connection
			SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();

			SOAPConnection soapConnection = soapConnectionFactory.createConnection();
			// Create SOAP Message
			MessageFactory messageFactory = MessageFactory.newInstance("SOAP 1.1 Protocol");
			SOAPMessage soapMessage = messageFactory.createMessage();
			MimeHeaders hd = soapMessage.getMimeHeaders();
			hd.addHeader("Authorization", "Basic UElURVNUOmNvbWFjMTIz");
			SOAPPart soapPart = soapMessage.getSOAPPart();

			// SOAP Envelope
			SOAPEnvelope envelope = soapPart.getEnvelope();
			envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

			// SOAP Body
			SOAPBody soapBody = envelope.getBody();
			SOAPElement soapBodyElem = soapBody.addChildElement("MT_MOM_QM_Request_Out", myNamespace);

			SOAPElement requestElem = soapBodyElem.addChildElement("ConditionalSentMateriel");

			requestElem.addChildElement("testNo").addTextNode(entity.getQarNo());
			requestElem.addChildElement("prepareUser").addTextNode(entity.getPrepareUser());
			String formatLocalDateTimeToString = TimeUtil.formatLocalDateTimeToString(TimeUtil.fomatDateToLocalDateTime(entity.getTestDate()));
			requestElem.addChildElement("testDate").addTextNode(formatLocalDateTimeToString);
			requestElem.addChildElement("department").addTextNode(entity.getDepartment());
			requestElem.addChildElement("materialDetail").addTextNode(entity.getMaterialDetail());
			requestElem.addChildElement("seller").addTextNode(entity.getSeller());
			requestElem.addChildElement("orderNo").addTextNode(entity.getOrderNo());
			requestElem.addChildElement("testFile").addTextNode(entity.getTestFile());
			requestElem.addChildElement("isUrgent").addTextNode(entity.getIsUrgent()== 1 ? "是":"否");
			requestElem.addChildElement("isExtraUrgent").addTextNode(entity.getIsExtraUrgent() == 1? "是":"否");
			String fomatDate = TimeUtil.fomatDate(entity.getNeedCompleteDate());
			requestElem.addChildElement("needCompleteDate").addTextNode(fomatDate);
			soapMessage.saveChanges();
			soapMessage.writeTo(System.out);
			// Send SOAP Message to SOAP Serve
			SOAPMessage soapResponse = soapConnection.call(soapMessage, "一个路径");
			soapResponse.writeTo(System.out);
			// 拿到结果
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			Source content = soapResponse.getSOAPPart().getContent();
			StreamResult result = new StreamResult(new ByteArrayOutputStream());
			transformer.transform(content, result);
			// 获取返回报文
			String s = ((ByteArrayOutputStream) result.getOutputStream()).toString();
			System.out.println("返回报文,如下：");
			System.out.print(s);
			JSONObject map = JSONObject.parseObject(s);
			System.out.println("结果：" + map.get("result") + "  内容：" + map.get("message"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
// 接收检验人员在完成实验送料任务后，QAR会将需要实验的信息发送给实验数据管理系统
	public ResultBean addSavePcdMaterialDescripList (QualityPclrTestInvoiceEntity testInvoiceEntity) {
		ResultBean resultBean = new ResultBean(true);
		long id = testInvoiceEntity.getId();
		QualityPclrTestInvoiceEntity entity = qualityPclrTestInvoiceDao.selectById(id);
		
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("taskDelegation_no", entity.getTestNo());
		map.put("delegation_name", entity.getDeliverUser());// 委托人就是收料人
		map.put("work_id", entity.getDeliverUserJobNumber());
		map.put("date", entity.getDeliverDate().toString());
		map.put("delegation_dept", entity.getDepartment());
		map.put("telephone", null);
		map.put("seller", entity.getSeller());
		map.put("batch", entity.getLotSize().toString());
		map.put("is_mat_test", "1");
		map.put("mat_no", entity.getTestFile());
		QueryWrapper<QualityQarCheckInvoiceEntity> query = new QueryWrapper<>();
		query.eq("qar_no", entity.getQarNo());
		QualityQarCheckInvoiceEntity selectOne = qualityQarCheckInvoiceDao.selectOne(query);
		QualitySapPurchaseOrderEntity selectOne2 = qualitySapPurchaseOrderDataHandler.selectBySome(selectOne.getMaterialNumber(), selectOne.getPartNo(), selectOne.getSerialNumber());
		
		Map<String,String> hashMap = new HashMap<String,String>();
		hashMap.put("materia_name", selectOne.getPartName());
		hashMap.put("materia_no", selectOne.getPartNo());
		hashMap.put("materia_status", selectOne2.getZhuangTaiXingShi());
		hashMap.put("materia_standard", selectOne2.getGuiFan());
		hashMap.put("materia_specification_size", selectOne2.getGuiGe());
		hashMap.put("lot_no", selectOne2.getVendorBatchNumber());
		hashMap.put("materia_num", selectOne2.getQuantity()+"");
		hashMap.put("materia_type", selectOne2.getXing());
		hashMap.put("materia_category", selectOne2.getLei());
		hashMap.put("materia_level", selectOne2.getJi());
		hashMap.put("bom_no", selectOne2.getMaterial());
		hashMap.put("materia_reel_no", null);
		hashMap.put("materia_blueprint_no", null);
		hashMap.put("fabrication_outline_no", null);
		hashMap.put("due_date", null);
		hashMap.put("other", null);
		map.put("list", hashMap);
		String json = JSONObject.toJSONString(map);
		try {
			Map<String, Object> invoke = SoapCallUtil.invoke("http://10.13.11.219/c919/web_service/services/IQualityService?wsdl", "sendQualityOrder", json);
			
			if (!invoke.get("result").equals("true")) {
				resultBean.setErrorMessge(invoke.get("message").toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultBean;
	}

}
